using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace BlockingCollectionConsoleApp
{
    public static class ProducerConsumerQueue
    {
        public static void Run()
        {
            var blockingCollection = new BlockingCollection<int>();
            var producer = Task.Factory.StartNew(() =>
                                                     {
                                                         for (var i = 1; i < 10; i++)
                                                             blockingCollection.Add(i);

                                                         blockingCollection.CompleteAdding();
                                                     });

            var consumer1 = Task.Factory.StartNew(() =>
                                                      {
                                                          foreach (var value in blockingCollection.GetConsumingEnumerable())
                                                              Console.WriteLine("Worker 1: " + value);
                                                      });

            var consumer2 = Task.Factory.StartNew(() =>
                                                      {
                                                          foreach (var value in blockingCollection.GetConsumingEnumerable())
                                                              Console.WriteLine("Worker 2: " + value);
                                                      });

            Task.WaitAll(producer, consumer1, consumer2);

            Console.WriteLine("Press any key to continue");
            Console.ReadKey(true);
        }
    }
}